import api from './api'
import DeviceStorage from '../utils/DeviceStorage'
import define from '../utils/define'
import Tips from 'react-native-root-tips';
import {DeviceEventEmitter} from 'react-native'

let common_url = api.baseUrl;  //服务器地址
let token = ''
DeviceStorage.get(define.token).then((args) => {
    if (args) {
        token = 'Bearer ' + args;
    } else {
        token = null;
    }
})

DeviceEventEmitter.addListener('loginToken', (args) => {
    if (args) {
        token = 'Bearer ' + args;
    } else {
        token = null;
    }
});
DeviceEventEmitter.addListener('loginOut', () => {
    token = null;
});

Tips.setDefaultOptions({
    showLoading: true,
    backgroundColor: 'gray',
    opacity: 0.95,
    textColor: 'white',
    durations: 1000

    // setting image you like
    // imageLoading: require('xxxxxxxxxx'),
    // imageSuccess: require('xxxxxxxxxx'),
    // imageFail: require('xxxxxxxxxx'),
    // imageInfo: require('xxxxxxxxxx'),
    // imageWarn: require('xxxxxxxxxx'),
});


export default class NetTool {


    static fetchGetRequest = async(url, method, params) => {


        let header = {
            "Authorization": token,  //用户登陆后返回的token，某些涉及用户数据的接口需要在header中加上token
        };
        if (params) {
            let paramsArray = [];
            //拼接参数
            Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
            if (url.search(/\?/) === -1) {
                url += '?' + paramsArray.join('&')
            } else {
                url += '&' + paramsArray.join('&')
            }
        }

        let response = await fetch(common_url + url, {
            method: method,
            headers: header,
        })
        console.log('NetTool----', response,header)

        if (response.status == 200) {

            let data = JSON.parse(response._bodyText)

            if (data.code) {
                if (url == 'getUserCourseList/') {

                } else {
                    Tips.showFail(data.message, {mask: true})
                }
            } else {
                return data;
            }
        } else {
            Tips.showFail('服务器开小差了...', {mask: true})
        }
    }
    static fetchPostRequest = async(url, method, params) => {


        let header = {
            "Authorization": token,  //用户登陆后返回的token，某些涉及用户数据的接口需要在header中加上token
        };
        let formData = new FormData();
        for (var key in params) {
            formData.append(key, params[key]);
        }

        let response = await fetch(common_url + url, {
            method: method,
            headers: header,
            body: formData,
        })
        console.log('NetTool', response)

        if (response.status == 200) {

            let data = JSON.parse(response._bodyText)

            if (data.code) {
                Tips.showFail(data.message, {mask: true})
            } else {
                return data;
            }
        } else {
            Tips.showFail('服务器开小差了...', {mask: true})
        }
    }

    static UploadHomeworkImage = async(params) => {

        let formData = new FormData();
        let file = {uri: params.path, type: 'image/jpeg', name: params.fileName};
        formData.append("file", file);
        let response = await fetch(api.baseUrl + 'api/upload/file', {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': token,
            },
            body: formData,
        })
        console.log('kisjsijs', response)

        if (response.status == 200) {

            return {data: JSON.parse(response._bodyText)};
        } else {
            Tips.showFail('服务器开小差了...', {mask: true})
        }

    }
}


